package se.jayway.millionaire.internal.game;

import java.util.ArrayList;
import java.util.List;

import se.jayway.millionaire.model.game.Answer;
import se.jayway.millionaire.model.game.Game;
import se.jayway.millionaire.model.game.GameSession;
import se.jayway.millionaire.model.game.Player;
import se.jayway.millionaire.model.repository.Solution;
import se.jayway.millionaire.model.repository.SolutionRepository;

public class SimpleGame implements Game, Runnable {
	private SolutionRepository repository;
	private boolean running;
	private final List<GameSession> gameSessions = new ArrayList<GameSession>();
	
	public SimpleGame(SolutionRepository repository) {
		this.repository = repository;
	}
	
	public void start() {
		Thread thread = new Thread(this);
		running = true;
		thread.start();
	}

	public void stop() {
		running = false;
	}
	
	public void run() {
		while (running) {
			System.out.println();
			System.out.println("------------------------");
			Solution solution = repository.nextSolution();

			System.out.println("GAME: Starting new game round");
			SimpleGameRound gameRound = newGameRound(solution);
			printGameRound(gameRound);
			gameRound.notifyNewGameRound();

			System.out.println("GAME: Wait for all players to answer or game round to end");
			gameRound.waitUntilFinished();
			gameRound.updateScoreCard();

			System.out.println("GAME: Notify correct answer");
			gameRound.notifyGameRoundFinished();
			gameRound.notifyWinners();
		}
	}

	private void printGameRound(SimpleGameRound gameRound) {
		System.out.println("Q: " + gameRound.getQuestion().getText());
		Answer[] answerAlternatives = gameRound.getQuestion().getAnswerAlternatives();
		for (int i = 0; i < answerAlternatives.length; i++) {
			System.out.println((i + 1) + ": " + answerAlternatives[i].getText());
		}
	}

	public GameSession newGameSession(Player player) {
		System.out.println(player + " joins the game");
		GameSession gameSession = new SimpleGameSession(this, player);
		gameSessions.add(gameSession);
		return gameSession;
	}

	public void endGameSession(GameSession gameSession) {
		System.out.println(gameSession.getPlayer() + " leaves the game");
		gameSessions.remove(gameSession);
	}
	
	private SimpleGameRound newGameRound(Solution solution) {
		return new SimpleGameRound(solution, gameSessions);
	}
}
